(function ($) {
    "use strict";

    $(".necessary").each(function () {
        $(this).append($('<span style="color:red;">&nbsp;*</span>'));
    });

    var mq_type_rocketmq = $('.mq-type-rocketmq');
    var mq_type_activemq = $('.mq-type-activemq');
    mq_type_activemq.detach();
    $('input[type=radio][name="mqType"]').change(function () {
        checkMQType();
    });

    Array.prototype.filter.call(document.getElementsByClassName('needs-validation'), function (form) {
        $(form).find('#submitForm').on('click', function (event) {
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            } else {
                submitForm();
            }
            form.classList.add('was-validated');
        });
        $(form).find('#resetForm').on('click', function (event) {
            event.preventDefault();
            form.classList.remove('was-validated');
        });
    });

    function checkMQType() {
        var mq_type = $('.mq-type');
        var mqTypeVal = $('input[type=radio][name="mqType"]:checked').val();
        if (mqTypeVal == 'R') {
            mq_type_activemq.detach();
            mq_type.after(mq_type_rocketmq);
            translate(mq_type_rocketmq);
        } else {
            mq_type_rocketmq.detach();
            mq_type.after(mq_type_activemq);
            translate(mq_type_activemq);
        }
    }

    function submitForm() {
        var mqType = $('input[type=radio][name="mqType"]:checked').val();
        var mqConfigId = $('input[name="mqConfigId"]').val();
        var data = {mqConfigId: mqConfigId, mqType: mqType};
        if (mqType === 'R') {
            data['mqNameServer'] = $('input[name="mqNameServer"]').val();
            data['mqProducerGroupName'] = $('input[name="mqProducerGroupName"]').val();
            data['mqConsumerGroupName'] = $('input[name="mqConsumerGroupName"]').val();
        } else {
            data['mqBrokerUrl'] = $('input[name="mqBrokerUrl"]').val();
            data['mqUser'] = $('input[name="mqUser"]').val();
            data['mqPassword'] = $('input[name="mqPassword"]').val();
        }
        axiosPost({
            url: '/schedule/mq/addMQConfig',
            data: data,
            success: function (result) {
                if ('fail' == result.status) {
                    showErrorNoty({translateFor: 'message.' + (result.msgCode || 'parameterNull')});
                } else {
                    newSuccessModal({
                        content: "modal.addMQConfigSuccess",
                        okFun: function () {
                            redirect('mqConfigDetail', mqConfigId);
                        }
                    });
                }
            }
        });
    }
})(jQuery);